<template>
    <div class="banner">
      <!-- 添加轮播图的表单 -->
      <el-form :model="formData" label-width="80px" style="width: 60%">
        <el-form-item label="标题">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            :action="action"   
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 160px; height: 80px;" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接">
          <el-input v-model="formData.link" placeholder="请输入链接" />
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker v-model="formData.startTime" type="datetime" placeholder="选择开始时间" />
          <el-date-picker v-model="formData.endTime" type="datetime" placeholder="选择结束时间" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave">提交</el-button>
        </el-form-item>
      </el-form>
  
  
  
  
      <table-pro :columns="columns" :requestApi="getBannerList">
        <template #image="{ row }">
          <img :src="row.image" alt="" style="width: 100px; height: 60px;" />
        </template>
        <template #expires="{ row }">
          {{ dayjs(row.startTime).format('YYYY-MM-DD HH:mm:ss') }} -
          {{ dayjs(row.endTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </table-pro>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref } from 'vue'
  import {  getBannerList, saveBanner } from '@/API/banner'
  import dayjs from 'dayjs'
  import useUserStore from "@/store/user"
  import { ElMessage } from 'element-plus'
  import type { UploadProps } from 'element-plus'
  

// 调用user仓库
  const store = useUserStore()
  const imageUrl = ref('')
  
  const columns: ITableColumn[] = [
    { prop: 'title', label: '标题', fixed: true },
    { prop: 'image', label: '图片', type: 'slot', width: '160px' },
    { prop: 'link', label: '链接', width: '360px' },
    { prop: 'expires', label: '有效期', type: 'slot' }
  ]
  
  // 表单数据
  const formData = ref({
    title: '',
    image: '',
    link: '',
    startTime: '',
    endTime: ''
  })
  
  // 文件上传时的后端接口 action 地址
  const action = import.meta.env.VITE_API_BASE_URL + '/api/v1/admin/files'
  // 发送上传请求时，需要在请求头中添加认证 token
  const headers = {
    Authorization: `Bearer ${store.token}`
  }
  /**
   * 图片上传成功
   */
  const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
  ) => {
    // 预览, 将上传成功的文件的地址赋值给 imageUrl
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    // 响应数据
    console.log('response:', response)
    formData.value.image = response.data.file
  }
  
  /**
   * 图片上传之前的校验
   */
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
    if (!types.includes(rawFile.type)) {
      ElMessage.error('Avatar picture must be JPG format!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('Avatar picture size can not exceed 2MB!')
      return false
    }
    return true
  }
  
  // 添加保存
  const handleSave = async () => {
    const result = await saveBanner(formData.value)
    console.log('保存结果:', result)
  }
  </script>
  
  <style lang="less">
  .avatar-uploader {
    width: 178px;
    height: 178px;
  
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
  
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
  
    img {
      width: 100%;
      height: 100%;
    }
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>